<template>
    <div class="activityPost">
        <div class="list">
            <div class="info">
                <div class="title">填写申请信息</div>
                <div class="input-item">
                    <div class="label">推广标题</div>
                    <input type="text" class="input" v-model="title" placeholder="请输入推广标题" />
                </div>
                <div class="input-item" @click="hotelShow = true">
                    <div class="label">推广酒店</div>
                    <!-- <input type="text" class="input" v-model="hotel" placeholder="例：天津海河英迪格酒店" readonly /> -->
                    <p class="input" v-if="hotel">{{ hotel }}</p>
                    <p class="input" v-else>例：天津海河英迪格酒店</p>
                    <img src="@/assets/youjiantou.png" alt="" class="icon" />
                </div>
                <div class="input-item" @click="startShow = true">
                    <div class="label">推广时段</div>
                    <p class="input" v-if="time.length == 2">{{ time[0].slice(0, 10) }} ~ {{ time[1].slice(0, 10) }}</p>
                    <p class="input" v-else>请选择</p>
                    <img src="@/assets/youjiantou.png" alt="" class="icon" />
                </div>
            </div>
            <div class="info">
                <div class="title">上传活动图片</div>
                <div class="uploader-wrapper">
                    <div v-if="image" class="suc_img">
                        <img :src="image" alt="" class="uploader-img-success" />
                        <img src="@/assets/upload_del.png" alt="" class="del-icon" @click.stop="image = ''" />
                    </div>
                    <van-uploader :max-count="1" :after-read="afterRead" v-if="!image">
                        <img src="@/assets/uploadimg.png" alt="" class="uploader-img" />
                        <div>建议上传图片大小:1920px*1080px</div>
                    </van-uploader>
                </div>
                <div class="uploader-wrapper">
                    <div v-if="pdf" class="suc_pdf">
                        <img src="@/assets/pdfFile.png" alt="" class="uploader-imgPdf" />
                        <div class="pdfName">{{ pdfName }}</div>
                        <div class="pdfDel" @click.stop="(pdf = ''), (pdfName = '')">删除</div>
                    </div>
                    <van-uploader :max-count="1" accept=".pdf" :after-read="afterReadPdf" v-if="!pdf">
                        <img src="@/assets/pdfFile.png" alt="" class="uploader-imgPdf" />
                        <div>上传PDF文件</div>
                    </van-uploader>
                </div>
            </div>
        </div>
        <div class="btn-wrapper" @click="save">
            <div class="btn">保存</div>
        </div>
        <van-popup v-model="startShow" position="bottom">
            <van-datetime-picker
                v-model="startDate"
                type="datetime"
                title="选择开始时间"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="startConfirm"
                @cancel="startCancel"
            />
        </van-popup>
        <van-popup v-model="endShow" position="bottom">
            <van-datetime-picker
                v-model="endDate"
                type="datetime"
                title="选择结束时间"
                :min-date="minEndDate"
                :max-date="maxDate"
                @confirm="endConfirm"
                @cancel="endCancel"
            />
        </van-popup>
        <van-popup v-model="hotelShow" position="bottom">
            <van-picker
                title="选择推广酒店"
                show-toolbar
                :columns="hotelList"
                @confirm="hotelConfirm"
                @cancel="hotelCancel"
            />
        </van-popup>
    </div>
</template>

<script>
import moment from "moment";
moment.locale("zh-cn");
import { Dialog, Toast } from "vant";
export default {
    name: "newActivityPost",
    data() {
        return {
            title: "",
            hotel: "",
            minDate: new Date(2020, 0, 1),
            minEndDate: new Date(2020, 0, 1),
            maxDate: new Date(2045, 10, 1),
            startDate: new Date(),
            endDate: new Date(),
            startShow: false,
            endShow: false,
            image: "",
            pdf: "",
            pdfName: "",
            time: [],
            hotelList: [], //酒店列表
            hotelShow: false,
        };
    },
    mounted() {
        this.getHotelList();
    },
    methods: {
        //获取酒店列表
        getHotelList() {
            this.$api
                .hotels()
                .then((res) => {
                    if (res.status_code != 200) {
                        Toast(res.message ? res.message : "获取错误");
                        return;
                    }
                    if (res.data.hotels.length == 0) {
                        return;
                    }
                    this.hotelList = res.data.hotels.map((item) => {
                        return item.hotel_name;
                    });
                })
                .catch((e) => {
                    Toast("获取错误");
                });
        },
        //确认选择酒店
        hotelConfirm(value) {
            this.hotel = value;
            this.hotelShow = false;
        },
        //取消选择酒店
        hotelCancel() {
            this.hotelShow = false;
        },
        //确认选择推广开始时间
        startConfirm(val) {
            this.time[0] = moment(val).format("YYYY-MM-DD HH:mm");
            this.minEndDate = val;
            this.startShow = false;
            this.endShow = true;
        },
        //取消选择推广开始时间
        startCancel() {
            this.startShow = false;
        },
        //确认选择推广结束时间
        endConfirm(val) {
            this.time[1] = moment(val).format("YYYY-MM-DD HH:mm");
            this.endShow = false;
        },
        //取消选择推广结束时间
        endCancel() {
            this.endShow = false;
        },
        //上传图片
        afterRead(file) {
            Toast.loading({
                message: "上传中...",
                forbidClick: true,
                duration: 0,
            });
            let quality = 1;
            let _this = this;
            let imgFile = file.file;
            if (imgFile.size > 500 * 1024) {
                quality = (500 * 1024) / file.size;
            }
            let img = new Image();
            img.src = file.content;
            img.onload = function() {
                let base64Img = _this.rotateImage(this, quality);
                let endFile = _this.dataURLtoFile(base64Img, imgFile.name.split(".")[0]);
                let formData = new FormData();
                formData.append("file", endFile);
                _this.$api
                    .upload(formData)
                    .then((res) => {
                        Toast.clear();
                        if (res.status_code == 200) {
                            // console.log(res);
                            _this.image = res.data;
                        } else {
                            Toast(res.message ? res.message : "上传错误");
                        }
                    })
                    .catch((e) => {
                        Toast.clear();
                        Toast("上传错误");
                    });
            };
        },
        //上传pdf
        afterReadPdf(file) {
            Toast.loading({
                message: "上传中...",
                forbidClick: true,
                duration: 0,
            });
            this.pdfName = file.file.name;

            let formData = new FormData();
            formData.append("file", file.file);
            this.$api
                .upload(formData)
                .then((res) => {
                    Toast.clear();
                    if (res.status_code == 200) {
                        console.log(res);
                        this.pdf = res.data;
                    } else {
                        Toast(res.message ? res.message : "上传错误");
                    }
                })
                .catch((e) => {
                    Toast.clear();
                    Toast("上传错误");
                });
        },
        //保存
        save() {
            if (!this.title) {
                Dialog({ message: "请先输入活动标题" });
                return;
            }
            if (!this.hotel) {
                Dialog({ message: "请先输入活动酒店" });
                return;
            }
            if (this.time.length != 2) {
                Dialog({ message: "请先选择活动时间" });
                return;
            }
            if (!this.image) {
                Dialog({ message: "请先上传活动图片" });
                return;
            }
            Toast.loading({
                message: "保存中...",
                forbidClick: true,
                duration: 0,
            });
            this.$api
                .activityStore({
                    title: this.title,
                    image: this.image,
                    pdf: this.pdf,
                    pdf_name: this.pdfName,
                    hotel: this.hotel,
                    start_time: this.time[0],
                    end_time: this.time[1],
                })
                .then((res) => {
                    this.desc = "";
                    this.type = {};
                    Toast.clear();
                    if (res.status_code == 200) {
                        Dialog({ message: "保存成功" }).then(() => {
                            this.$router.go(-1);
                        });
                    } else {
                        Dialog({ message: res.message });
                    }
                });
            // this.$router.go(-1);
        },
        //旋转图片
        rotateImage(image, quality) {
            let _this = this;
            let width = image.width;
            let height = image.height;

            let canvas = document.createElement("canvas");
            let ctx = canvas.getContext("2d");
            let newImage = new Image();
            let imageDate;

            _this.Exif.getData(image, function() {
                //  _this.Exif.getAllTags(this);
                var orientation = _this.Exif.getTag(this, "Orientation");
                console.log(orientation);
                let userAgent = navigator.userAgent.toLowerCase();
                let ios = userAgent.match(/cpu iphone os (.*?) like mac os/);
                let reg = /.*\..*/; //判断是否有小数点
                if (!ios) {
                    canvas.height = height;
                    canvas.width = width;
                    ctx.drawImage(image, 0, 0);
                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                    newImage.src = imageDate;
                } else {
                    let iosVersion = ios[1].replace(/_/g, "."); //获取ios系统版本
                    if (Number(iosVersion.split(".")[0]) < 13) {
                        switch (orientation) {
                            case 6:
                                console.log("旋转90°");
                                canvas.height = width;
                                canvas.width = height;
                                ctx.rotate(Math.PI / 2);

                                ctx.drawImage(image, 0, -height);
                                imageDate = canvas.toDataURL("Image/jpeg", quality);
                                newImage.src = imageDate;
                                break;
                            case 3:
                                console.log("旋转180°");
                                canvas.height = height;
                                canvas.width = width;
                                ctx.rotate(Math.PI);

                                ctx.drawImage(image, -width, -height);
                                imageDate = canvas.toDataURL("Image/jpeg", quality);
                                newImage.src = imageDate;
                                break;
                            case 8:
                                console.log("旋转270°");
                                canvas.height = width;
                                canvas.width = height;
                                ctx.rotate(-Math.PI / 2);

                                ctx.drawImage(image, -height, 0);
                                imageDate = canvas.toDataURL("Image/jpeg", quality);
                                newImage.src = imageDate;
                                break;
                            default:
                                console.log("不旋转");
                                canvas.height = height;
                                canvas.width = width;
                                ctx.drawImage(image, 0, 0);
                                imageDate = canvas.toDataURL("Image/jpeg", quality);
                                newImage.src = imageDate;
                                break;
                        }
                    } else if (Number(iosVersion.split(".")[0]) > 13) {
                        //正常
                        canvas.height = height;
                        canvas.width = width;
                        ctx.drawImage(image, 0, 0);
                        imageDate = canvas.toDataURL("Image/jpeg", quality);
                        newImage.src = imageDate;
                    } else {
                        //等于13 判断ios系统有无.
                        if (reg.test(iosVersion)) {
                            if (Number(iosVersion.split(".")[1]) < 4) {
                                //需要调整旋转
                                switch (orientation) {
                                    case 6:
                                        console.log("旋转90°");
                                        canvas.height = width;
                                        canvas.width = height;
                                        ctx.rotate(Math.PI / 2);

                                        ctx.drawImage(image, 0, -height);
                                        imageDate = canvas.toDataURL("Image/jpeg", quality);
                                        newImage.src = imageDate;
                                        break;
                                    case 3:
                                        console.log("旋转180°");
                                        canvas.height = height;
                                        canvas.width = width;
                                        ctx.rotate(Math.PI);

                                        ctx.drawImage(image, -width, -height);
                                        imageDate = canvas.toDataURL("Image/jpeg", quality);
                                        newImage.src = imageDate;
                                        break;
                                    case 8:
                                        console.log("旋转270°");
                                        canvas.height = width;
                                        canvas.width = height;
                                        ctx.rotate(-Math.PI / 2);

                                        ctx.drawImage(image, -height, 0);
                                        imageDate = canvas.toDataURL("Image/jpeg", quality);
                                        newImage.src = imageDate;
                                        break;
                                    default:
                                        console.log("旋转90°2");
                                        canvas.height = height;
                                        canvas.width = width;
                                        ctx.drawImage(image, 0, 0);
                                        imageDate = canvas.toDataURL("Image/jpeg", quality);
                                        newImage.src = imageDate;
                                        break;
                                }
                            } else {
                                canvas.height = height;
                                canvas.width = width;
                                ctx.drawImage(image, 0, 0);
                                imageDate = canvas.toDataURL("Image/jpeg", quality);
                                newImage.src = imageDate;
                            }
                        } else {
                            switch (orientation) {
                                case 6:
                                    console.log("旋转90°");
                                    canvas.height = width;
                                    canvas.width = height;
                                    ctx.rotate(Math.PI / 2);

                                    ctx.drawImage(image, 0, -height);
                                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                                    newImage.src = imageDate;
                                    break;
                                case 3:
                                    console.log("旋转180°");
                                    canvas.height = height;
                                    canvas.width = width;
                                    ctx.rotate(Math.PI);

                                    ctx.drawImage(image, -width, -height);
                                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                                    newImage.src = imageDate;
                                    break;
                                case 8:
                                    console.log("旋转270°");
                                    canvas.height = width;
                                    canvas.width = height;
                                    ctx.rotate(-Math.PI / 2);

                                    ctx.drawImage(image, -height, 0);
                                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                                    newImage.src = imageDate;
                                    break;
                                default:
                                    console.log("不旋转");
                                    canvas.height = height;
                                    canvas.width = width;
                                    ctx.drawImage(image, 0, 0);
                                    imageDate = canvas.toDataURL("Image/jpeg", quality);
                                    newImage.src = imageDate;
                                    break;
                            }
                        }
                    }
                }
            });
            return imageDate;
        },
        //将base64转换为文件
        dataURLtoFile(dataurl, filename) {
            var arr = dataurl.split(","),
                mime = arr[0].match(/:(.*?);/)[1],
                bstr = atob(arr[1]),
                n = bstr.length,
                u8arr = new Uint8Array(n);

            while (n--) {
                u8arr[n] = bstr.charCodeAt(n);
            }

            return new File([u8arr], filename, {
                type: mime,
            });
        },
    },
};
</script>

<style lang="scss">
.activityPost {
    .van-button {
        height: 54px;
    }
    .van-button--normal {
        font-size: 16px;
    }
}
</style>
<style lang="scss" scoped>
.activityPost {
    height: 100vh;
    background-color: #ebf1f4;
    position: relative;
    z-index: 2;

    .list {
        width: 100%;
        height: calc(100vh - 2.1333rem);
        overflow-y: scroll;
        padding: 0.2667rem;

        .info {
            background: #ffffff;
            border-radius: 0.4rem;
            padding: 0.5333rem 0.32rem;
            margin-bottom: 0.2667rem;

            .title {
                font-weight: bold;
                font-size: 0.4267rem;
                color: #1f4456;
            }

            .input-item {
                margin-top: 0.5333rem;
                height: 1.3333rem;
                background: #f5f8fa;
                border-radius: 0.2667rem;
                display: flex;
                align-items: center;
                padding: 0 0.4rem;

                .label {
                    width: 1.6rem;
                    font-weight: 500;
                    font-size: 0.3733rem;
                    color: #1e1e1e;
                }

                .input {
                    background-color: transparent;
                    font-weight: 500;
                    font-size: 0.3733rem;
                    color: #999999;
                    flex: 1;
                }

                .icon {
                    width: 0.2rem;
                    height: 0.32rem;
                }
            }

            .uploader-wrapper {
                height: 4.9467rem;
                background: #f5f8fa;
                border-radius: 0.2667rem;
                border: 1px solid #dadce0;
                margin-top: 0.5333rem;
                margin-bottom: 0.2667rem;

                ::v-deep .van-uploader,
                ::v-deep .van-uploader__wrapper,
                ::v-deep .van-uploader__upload,
                ::v-deep .van-uploader__input-wrapper {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    justify-content: center;
                    align-items: center;
                    font-weight: 500;
                    font-size: 0.32rem;
                    color: #a1adb3;

                    .uploader-img {
                        width: 1.12rem;
                        height: 0.9067rem;
                        margin-bottom: 0.5333rem;
                    }

                    .uploader-imgPdf {
                        width: 0.8533rem;
                        height: 0.9733rem;
                        margin-bottom: 0.5333rem;
                    }
                }

                .suc_img {
                    width: 100%;
                    height: 100%;
                    position: relative;

                    .del-icon {
                        position: absolute;
                        right: 0;
                        top: 0;
                    }

                    .uploader-img-success {
                        width: 100%;
                        height: 100%;
                    }
                }

                .suc_pdf {
                    width: 100%;
                    height: 100%;
                    display: flex;
                    flex-direction: column;
                    align-items: center;
                    justify-content: center;

                    .uploader-imgPdf {
                        width: 0.8533rem;
                        height: 0.9733rem;
                        margin-bottom: 0.5333rem;
                    }

                    .pdfName {
                        font-weight: 500;
                        font-size: 0.32rem;
                        color: #1f4456;
                    }

                    .pdfDel {
                        font-weight: 500;
                        font-size: 0.32rem;
                        color: #e8542c;
                        margin-top: 0.5333rem;
                    }
                }
            }
        }
    }

    .btn-wrapper {
        width: 100%;
        height: 2.1333rem;
        background-color: #fff;
        padding: 0.2667rem 0.4rem 0 0.4rem;

        .btn {
            width: 100%;
            height: 1.2rem;
            background: #2a4347;
            border-radius: 0.2667rem;
            border: 1px solid #cdcdcd;
            font-weight: 500;
            font-size: 0.4267rem;
            color: #ffffff;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    }
}
</style>
